package com.zhuiyun.project.api.system.user.controller;

import com.zhuiyun.project.annotation.OptLog;
import com.zhuiyun.project.api.system.role.entity.SysRole;
import com.zhuiyun.project.api.system.role.service.SysRoleService;
import com.zhuiyun.project.api.system.user.entity.SysUser;
import com.zhuiyun.project.api.system.user.service.SysUserService;
import com.zhuiyun.project.common.controller.BaseController;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.security.jwt.JWTConfig;
import com.zhuiyun.project.utils.RedisUtil;
import com.zhuiyun.project.utils.SecurityUtils;
import com.zhuiyun.project.utils.StringUtils;
import com.zhuiyun.project.utils.constants.CommonConstants;
import com.zhuiyun.project.utils.pageUtil.PageRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.parameters.P;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName SysUserController
 * @Description TODO
 * @Author Acer
 * @Date 2023/10/26 15:40
 **/
@RestController
@RequestMapping("/sysUser")
@Api(value = "用户管理")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    /**
      * @Author hyp
      * @Description 用户详情分页查询
      * @Date 2023/10/30 9:21
      * @Return com.zhuiyun.project.common.response.CommonResult
      * @param pageRequest
      * @param user
    */
    @ApiOperation(value = "用户详情分页查询")
    @OptLog(modular = "用户管理" , type = CommonConstants.SELECT , describe = "用户详情分页查询")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public CommonResult listUsers(PageRequest pageRequest, SysUser user){
        return CommonResult.ok(userService.listUsers(pageRequest,user));
    }

    /**
      * @Author hyp
      * @Description 添加用户
      * @Date 2023/10/30 9:24
      * @Return com.zhuiyun.project.common.response.CommonResult
      * @param user
    */
    @ApiOperation(value = "添加用户")
    @OptLog(modular = "用户管理" , type = CommonConstants.ADD , describe = "添加用户")
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @PostMapping
    public CommonResult addUser(@Validated @RequestBody SysUser user){
        if (!userService.checkLoginNameUnique(user)){
            return CommonResult.error("添加用户" + user.getLoginName()+"失败，用户名已存在");
        }else if (!userService.checkPhoneUnique(user)){
            return CommonResult.error("添加用户" + user.getPhone()+"失败，手机号已存在");
        }else if(!userService.checkEmailUnique(user)){
            return CommonResult.error("添加用户" + user.getEmail()+"失败，邮箱已存在");
        }
        return CommonResult.ok(userService.addUser(user));
    }

    /**
      * @Author hyp
      * @Description 根据用户编号获取详情信息
      * @Date 2023/10/30 9:27
      * @Return com.zhuiyun.project.common.response.CommonResult
      * @param id
    */
    @ApiOperation(value = "根据用户编号获取详细信息")
    @OptLog(modular = "用户管理" , type = CommonConstants.SELECT , describe = "根据用户编号获取详情信息")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/","/{userId}"})
    public CommonResult getInfoUserByid(@PathVariable(value = "userId", required = false ) Integer id){
        List<SysRole> roles = roleService.selectRoleAll();
        HashMap<String,Object> map = new HashMap<>();
        map.put("roles", roles);
        if (StringUtils.isNotNull(id))
        {
            SysUser sysUser = userService.selectUserById(id);
            map.put("sysUser", sysUser);
            map.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return CommonResult.ok(map);
    }

    /**
      * @Author hyp
      * @Description 根据用户编号删除用户
      * @Date 2023/10/30 9:31
      * @Return com.zhuiyun.project.common.response.CommonResult
      * @param userids
    */
    @ApiOperation(value = "根据用户编号删除用户")
    @OptLog(modular = "用户管理" , type = CommonConstants.DELETE , describe = "根据用户编号删除用户")
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @DeleteMapping("/{userIds}")
    public CommonResult removeUserByIds(@PathVariable("userIds") Integer[] userids){
        if (ArrayUtils.contains(userids,getUserId())){
            return CommonResult.error("当前用户不能删除");
        }
        return userService.removeUserByIds(userids);
    }

    /**
      * @Author hyp
      * @Description 修改用户
      * @Date 2023/10/30 9:31
      * @Return com.zhuiyun.project.common.response.CommonResult
      * @param user
    */
    @ApiOperation(value = "修改用户")
    @OptLog(modular = "用户管理" , type = CommonConstants.UPDATE , describe = "修改用户")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping
    public CommonResult editUser(@Validated @RequestBody SysUser user){
//        userService.checkUserAllowed(user);
        if (!userService.checkLoginNameUnique(user)){
            return CommonResult.error("修改用户" + user.getLoginName()+"失败，用户名已存在");
        }else if (!userService.checkPhoneUnique(user)){
            return CommonResult.error("修改用户" + user.getPhone()+"失败，手机号已存在");
        }else if(!userService.checkEmailUnique(user)){
            return CommonResult.error("修改用户" + user.getEmail()+"失败，邮箱已存在");
        }
        return CommonResult.ok(userService.editUser(user));
    }

    /**
      * @Author hyp
      * @Description 修改用户状态
      * @Date 2023/10/30 9:33
      * @Return com.zhuiyun.project.common.response.CommonResult
      * @param user
    */
    @ApiOperation(value = "修改用户状态")
    @OptLog(modular = "用户管理" , type = CommonConstants.UPDATE , describe = "修改用户状态")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping("/changeStatus")
    public CommonResult changeStatusUser(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        return CommonResult.ok(userService.changeStatusUser(user));
    }


    /**
      * @Author hyp
      * @Description 查询未分配用户的角色
      * @Date 2023/11/2 9:48
      * @Return com.zhuiyun.project.common.response.CommonResult
      * @param userId
    */
    @ApiOperation(value = "查询未分配用户的角色")
    @OptLog(modular = "用户管理" , type = CommonConstants.ADD , describe = "查询未分配用户的角色")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public CommonResult listAuthRoles(@PathVariable("userId") Integer userId){
        HashMap<Object,Object> hashMap = new HashMap<>();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        hashMap.put("user",user);
        hashMap.put("roles",SysUser.isAdmin(userId) ? roles : roles.stream().filter(r ->!r.isAdmin()).collect(Collectors.toList()));
        return CommonResult.ok(hashMap);
    }

    /**
      * @Author hyp
      * @Description 用户分配角色
      * @Date 2023/11/3 8:26
      * @Return com.zhuiyun.project.common.response.CommonResult
      * @param userId
      * @param roleIds
    */
    @ApiOperation(value = "用户分配角色")
    @OptLog(modular = "用户管理" , type = CommonConstants.ADD , describe = "用户分配角色")
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @PutMapping("/authRole")
    public CommonResult addAuthRole(Integer userId , Long[] roleIds){
        return CommonResult.ok(userService.addAuthRole(userId,roleIds));
    }

    /**
      * @Author hyp
      * @Description 重置密码
      * @Date 2023/11/3 8:26
      * @Return com.zhuiyun.project.common.response.CommonResult
      * @param user
    */
    @ApiOperation(value = "重置密码")
    @OptLog(modular = "用户管理" , type = CommonConstants.ADD , describe = "重置密码")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PutMapping("/resetPwd")
    public CommonResult editResetPwd(@RequestBody SysUser user){
        userService.checkUserAllowed(user);
        return CommonResult.ok(userService.resetPwd(user));
    }
}
